<template>
  <el-card
    v-if="userInfo"
    style="width: 600px; margin: 20px; margin-left: auto; margin-right: auto"
  >
    <el-form
      :model="userInfo"
      :label-position="labelPosition"
      label-width="80px"
    >
      <el-form-item label="姓名">
        <el-input v-model="userInfo.username" :readonly="!isEditing" />
      </el-form-item>
      <el-form-item label="学院">
        <el-input v-model="userInfo.college" :readonly="!isEditing" />
      </el-form-item>
      <el-form-item label="专业">
        <el-input v-model="userInfo.major" :readonly="!isEditing" />
      </el-form-item>
      <el-form-item label="年级">
        <el-input v-model="userInfo.grade" :readonly="!isEditing" />
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input v-model="userInfo.contactInfo" :readonly="!isEditing" />
      </el-form-item>
      <el-form-item label="自我介绍">
        <el-input
          type="textarea"
          v-model="userInfo.selfIntroduction"
          :readonly="!isEditing"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-if="!isEditing" type="primary" @click="startEditing"
          >编辑</el-button
        >
        <el-button v-else type="primary" @click="saveProfile">保存</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useTokenStore } from "@/stores/token.js";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";

const labelPosition = ref("right");
const isEditing = ref(false);

const tokenStore = useTokenStore();

const uploadHeaders = {
  Authorization: "Bearer " + tokenStore.getToken(),
};

const userInfo = ref({
  name: "",
  college: "",
  major: "",
  grade: "",
  contact: "",
  introduction: "",
});

const startEditing = () => {
  isEditing.value = true;
};

const saveProfile = async () => {
  try {
    const response = await request.put(
      "/api/user/updateUserInfo",
      userInfo.value,
      {
        headers: uploadHeaders,
      }
    );
    console.log("保存成功：", response.data);
    ElMessage.success("编辑成功");
    isEditing.value = false;
  } catch (error) {
    console.error("保存用户信息时出错：", error);
    // 在这里处理保存失败的情况，可以根据错误信息进行相应的处理
  }
};

onMounted(async () => {
  try {
    const response = await request.get("/api/user/userInfo", {
      headers: uploadHeaders,
    });
    console.log("响应数据：", response.data);
    userInfo.value = response.data;
    console.log("userInfo 数据：", userInfo.value);
  } catch (error) {
    console.error("获取用户信息时出错：", error);
    // 在这里处理请求失败的情况，可以根据错误信息进行相应的处理
  }
});
</script>
